const Route = require('../../enhance/route').Route
const MemStores = require('../../enhance/mem-stores').MemStores

Page({

  data: {
    HOST: 'http://192.168.1.7:3000',
    editIndex: -1,
    type: '',
    barcode: '',
    filePath: '',
    amount: 1
  },

  onLoad(options) {

    let { editIndex, type, barcode, filePath, amount } = options

    this.setData({
      type,
      editIndex: (editIndex > -1) ? editIndex : -1,
      amount: amount || 1,
      filePath: filePath || '',
      barcode: barcode || ''
    })
  },

  decrease(e) {

    let { amount } = this.data
    if (amount > 1) amount--;

    this.setData({ amount })
  },

  increase(e) {

    let { amount } = this.data
    amount++;

    this.setData({ amount })
  },

  amountChanged(e) {
    let amount = parseInt(e.detail.value)
    this.setData({ amount })
  },

  preview(e) {
    wx.previewImage({
      urls: [this.data.filePath]
    })
  },

  save() {

    let { editIndex, type, barcode, filePath, amount } = this.data
    let items = MemStores.get('todo-items')

    if (editIndex > -1) {
      let item = items[editIndex];
      item.amount = amount;
    }
    else {
      if (type == 'snap') {
        items.push({ type, filePath, amount })
      }
      else if (type == 'scan') {
        items.push({ type, barcode, amount })
      }
    }
  },

  saveThenBack(e) {
    this.save()
    Route.back()
  },

  saveThenSnap(e) {

    this.save()

    this.setData({ amount: 1, editIndex: -1 })
    let self = this

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: res => {
        const filePath = res.tempFilePaths[0]
        let type = 'snap'
        self.setData({ type, filePath })
      }
    })
  },

  saveThenScan(e) {

    this.save()

    this.setData({ amount: 1, editIndex: -1 })
    let self = this

    wx.scanCode({
      onlyFromCamera: true,
      scanType: ['barCode'],
      success: res => {
        let type = 'scan'
        let barcode = res.result
        if (barcode.length != 13) {
          wx.showToast({ icon: 'none', title: '请对照商品条形码进行扫描！' })
          setTimeout(() => { self.scan({}) }, 0);
        }
        else {
          self.setData({ type, barcode })
        }
      }
    })
  },

  remove(e) {

    let editIndex = parseInt(this.data.editIndex)

    if (editIndex > -1) {

      let items = MemStores.get('todo-items')

      if (items.length > editIndex) {
        items.splice(editIndex, 1)
        Route.back()
      }
    }
  }
})